﻿using System.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MG.SmartHMI.Domain;
using MG.SmartHMI.Entity.DAO;
using MG.SmartHMI.Model.Common;

namespace MG.SmartHMI.Model
{
    public partial class AxisBoxViewModel : BaseItemsControl
    {
        private AxisConfig AxisData { get; set; }

        public AxisBoxViewModel(AxisConfig data)
        {
            AxisData = data;
            Name = AxisData.Name ?? "新建轴";
        }

        public AxisBoxViewModel()
        {
            AxisData = new();
        }

        /// <summary>
        /// 使能
        /// </summary>
        [ObservableProperty]
        [Description("使能")]
        private bool switchOnAxis;

        /// <summary>
        /// 速度
        /// </summary>
        [ObservableProperty]
        [Description("速度 ")]
        private string vel = "0";

        /// <summary>
        /// 位置
        /// </summary>
        [ObservableProperty]
        [Description("位置 ")]
        private string position;

        partial void OnSwitchOnAxisChanged(bool value)
        { Task.Run(() => ModbusCtrl.Instance.UnitWrite(EnumDataType.BOOL, AxisData.EnableAddress, value.ToString())); }

        partial void OnVelChanged(string value)
        { Task.Run(() => ModbusCtrl.Instance.UnitWrite(EnumDataType.BOOL, AxisData.VelAddress, value.ToString())); }

        [RelayCommand]
        private void GOHome()
        { Task.Run(() => ModbusCtrl.Instance.WriteByTrigger(AxisData.HomeAddress, EnumTriggerType.UpEdge)); }

        [RelayCommand]
        private void JOGPStart()
        { Task.Run(() => ModbusCtrl.Instance.UnitWrite(EnumDataType.BOOL, AxisData.JOGPAddress, true.ToString())); }

        [RelayCommand]
        private void JOGPStop()
        { Task.Run(() => ModbusCtrl.Instance.UnitWrite(EnumDataType.BOOL, AxisData.JOGPAddress, false.ToString())); }

        [RelayCommand]
        private void JOGNStart()
        { Task.Run(() => ModbusCtrl.Instance.UnitWrite(EnumDataType.BOOL, AxisData.JOGNAddress, true.ToString())); }

        [RelayCommand]
        private void JOGNStop()
        { Task.Run(() => ModbusCtrl.Instance.UnitWrite(EnumDataType.BOOL, AxisData.JOGNAddress, false.ToString())); }

        public override void UpdateRead()
        { Position = ModbusCtrl.Instance.UnitRead(EnumDataType.FLOAT, AxisData.PositionAddress).Content; }
    }
}